package java_DesignPattern.CreatorPattern.SingletonPattern.tryDestruction.serialization;

import java.io.*;

/**
 * 测试通过序列化来破环单例模式
 */
public class Test {

    public static void main(String[] args) throws Exception {

        String fileName = "D:\\svn\\BestStudy\\Object.txt";

        //获取单例实例
        Singleton instance = Singleton.getInstance();

        //将单例实例写入文件
        //writeObjectToFile(instance, fileName);

        //从文件中读取对象
        Singleton instance1 = readObjectFromFile(fileName);

        //判断两个实例是否相等
        System.out.println(instance == instance1);
    }

    /**
     * 将对象写入文件
     * @param instance 要写入的对象
     * @param fileName 文件名
     * @throws Exception 可能抛出的异常
     */
    public static void writeObjectToFile(Singleton instance, String fileName) throws Exception {

        //创建对象输出流,将对象写入文件
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName));
        //将对象写入文件
        oos.writeObject(instance);
        //关闭对象输出流
        oos.close();
    }

        /**
         * 从文件中读取对象
         * @param fileName 文件名
         * @return 读取到的对象
         * @throws Exception 可能抛出的异常
         */
    public static Singleton readObjectFromFile(String fileName) throws Exception {

        //创建对象输入流,从文件中读取对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));
        //从文件中读取对象
        Singleton instance = (Singleton) ois.readObject();
        //关闭对象输入流
        ois.close();
        return instance;
    }
}
